#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);


    //初始化网络socket
    m_socket = new QTcpSocket(this);
    connect(m_socket, &QTcpSocket::connected, this, &MainWindow::onConnected);
    connect(m_socket, &QTcpSocket::disconnected, this, &MainWindow::onDisconnected);
    connect(m_socket, &QTcpSocket::readyRead, this, &MainWindow::onReadyRead);
    connect(m_socket, &QTcpSocket::errorOccurred, this, &MainWindow::onSocketError);

    //获取当前应用程序所在目录
    m_strDataPath=QApplication::applicationDirPath()+"/data/";
    qDebug()<<m_strDataPath;
    QDir d(m_strDataPath);
    if(!d.exists())//可以使用exists()函数检查文件或目录是否存在
    {
        d.mkdir(m_strDataPath);//若不存在，则照着该路径创建一个文件夹
    }
    m_model=new QStandardItemModel;
    connect(&m_timer,&QTimer::timeout,this,&MainWindow::updateFile);
    m_timer.start(1000);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);//不能直接修改表格的元素
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);//每次选中会选中一行
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//让m_model自适应占满tableView
    updateFile();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initConnections()
{

}
void MainWindow::updateFile()
{
    QDir d(m_strDataPath);
    QStringList lFilter;
    //lFilter<<"*.txt"<<"*.md";
    lFilter<<"*.*";
    lFilesInfo=d.entryInfoList(QDir::Files|QDir::Dirs|QDir::NoDotAndDotDot);//过滤器，
    //QString strFilter=ui->lineEdit->text();

    QString strFlag;
    QList<QStandardItem*> lRow;
    QStandardItemModel *m_temModel=new QStandardItemModel;
    for(int i=0;i<lFilesInfo.size();i++)
    {
        lRow.clear();
        QFileInfo &info=lFilesInfo[i];
        // if(!info.completeBaseName().contains(strFilter))
        // {
        //     continue;
        // }
        QStandardItem *p1=new QStandardItem(QString::number(i+1));
        QStandardItem *p2=new QStandardItem(info.isDir()?"文件夹":info.completeSuffix());//文件类型
        strFlag=strFlag+info.absoluteFilePath();
        QStandardItem *p3=new QStandardItem(info.absoluteFilePath());//文件绝对路径
        QStandardItem *p4=new QStandardItem(info.isDir()?info.fileName():info.baseName());//文件名称
        QStandardItem *p5=new QStandardItem(info.birthTime().toString("yyyy/MM/dd hh:mm:ss"));//文件创建时间
        QStandardItem *p6=new QStandardItem(info.lastModified().toString("yyyy/MM/dd hh:mm:ss"));//文件最后修改时件
        QStandardItem *p7=new QStandardItem(info.isDir()?"--":QString::number(info.size()/1024)+"KB");//文件大小
        lRow<<p1<<p2<<p3<<p4<<p5<<p6<<p7;
        m_temModel->appendRow(lRow);
    }
    if(strFlag==m_cur)
    {
        delete m_temModel;
        return;
    }
    delete m_model;
    m_model=nullptr;
    m_model=m_temModel;
    m_cur=strFlag;
    //m_temModel.clear();
    //在QTableView的属性编译器中的horizontalHeaderVisible可以打开或关闭水平表头
    //在QTableView的属性编辑器中的verticalHeaderVisible可以打开或关闭垂直表头
    //m_model.clear();
    //m_model=m_temModel;
    QStringList l;
    l<<"序号"<<"文件类型"<<"绝对路径"<<"文件名"<<"创建日期"<<"最后修改时间"<<"文件大小";
    m_model->setHorizontalHeaderLabels(l);
    ui->tableView->setModel(m_model);
    //ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);//不能直接修改表格的元素



}

void MainWindow::on_btn_search_clicked()
{
    m_strDataPath=ui->lineEdit->text();
    qDebug()<<m_strDataPath;
    updateFile();
}


void MainWindow::on_btn_loadDir_clicked()
{

    // 打包目录数据 - 只存储文件名
    QByteArray packageData;
    QDataStream out(&packageData, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_6_5);

    // 1. 写入文件头标识 (4字节)
    out.writeRawData("FLST", 4); // File List 的缩写


    // 3. 写入目录路径
    out << m_strDataPath;

    // 4. 写入文件数量
    out << quint32(lFilesInfo.size());
    qDebug() << "Total files/dirs to package:" << lFilesInfo.size();

    // 5. 只写入文件名/目录名
    for(const QFileInfo &info : lFilesInfo) {
        out << info.fileName(); // 只存储文件名/目录名
        qDebug() << "Packaged name:" << info.fileName();
    }

    // 6. 写入结束标记 (4字节)
    out.writeRawData("FEND", 4); // File END 的缩写

    qDebug() << "Binary package size:" << packageData.size() << "bytes";
    qDebug() << "Hex header:" << packageData.left(10).toHex();

    // 在本地备份一份
    QString backupPath = QApplication::applicationDirPath()+"/data/output.dat";
    m_lastPath=backupPath;
    QFile backupFile(backupPath);
    if (backupFile.open(QIODevice::WriteOnly)) {
        backupFile.write(packageData);
        backupFile.close();
        qDebug() << "Backup saved to:" << backupPath;

        // 显示成功消息
        QMessageBox::information(this, "备份成功",
                                 QString("文件名列表已打包为二进制文件\n"
                                         "备份路径: %1\n"
                                         "包含项目: %2 个\n"
                                         "文件大小: %3 字节")
                                     .arg(backupPath)
                                     .arg(lFilesInfo.size())
                                     .arg(packageData.size()));
    } else {
        QMessageBox::warning(this, "备份失败",
                             QString("无法创建备份文件:\n%1").arg(backupPath));
    }
}



void MainWindow::on_btn_send_clicked()
{
    // 检查是否有备份文件
    QString backupPath = QApplication::applicationDirPath()+"/data/output.dat";
    QFile backupFile(backupPath);
    if (!backupFile.exists()) {
        QMessageBox::warning(this, "错误", "没有找到备份文件，请先打包目录");
        return;
    }

    // 读取备份文件内容
    if (!backupFile.open(QIODevice::ReadOnly)) {
        QMessageBox::warning(this, "错误", "无法打开备份文件");
        return;
    }

    QByteArray fileData = backupFile.readAll();
    backupFile.close();

    // 获取服务器地址和端口
    QString serverAddr = ui->lb_Url->text();
    quint16 port = ui->lb_port->text().toUShort();

    qDebug()<<serverAddr;
    qDebug()<<port;
    if (serverAddr.isEmpty()) {
        QMessageBox::warning(this, "错误", "请输入服务器地址");
        return;
    }

    // 连接服务器
    m_socket->connectToHost(serverAddr, port);
    m_lastPath = backupPath; // 保存当前发送的文件路径
}

void MainWindow::onConnected()
{
    // 读取备份文件内容
    QFile backupFile(m_lastPath);
    if (!backupFile.open(QIODevice::ReadOnly)) {
        QMessageBox::warning(this, "错误", "无法打开备份文件");
        return;
    }

    QByteArray fileData = backupFile.readAll();
    backupFile.close();

    // 发送文件数据
    m_socket->write(fileData);
    qDebug() << "File data sent to server, size:" << fileData.size();
}

void MainWindow::onDisconnected()
{
    qDebug() << "Disconnected from server";
}

void MainWindow::onReadyRead()
{
    QByteArray response = m_socket->readAll();
    QMessageBox::information(this, "服务器响应", QString(response));
}

void MainWindow::onSocketError(QAbstractSocket::SocketError error)
{
    QMessageBox::warning(this, "网络错误", m_socket->errorString());
    qDebug()<<m_socket->errorString();
}

